package com.interview.javabasic;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

/*
@李子宁
Happy,happy everyday!
冲鸭！
2021/3/22

*/
public class SHA_HAX {

    public static void main(String[] args) throws UnsupportedEncodingException {
        // ************* 步骤 1：拼接规范请求串 *************
        String httpRequestMethod = "POST";
        String canonicalUri = "/industry-cgi";
        String canonicalQueryString = "";
        String canonicalHeaders = "content-type:application/json; charset=utf-8\n";
        String signedHeaders = "content-type";

        String payload = "{\"remark\": \"\", \"product_name\": \"test1\"}";
        String canonicalRequest = httpRequestMethod + "\n" + canonicalUri
                + "\n" + canonicalQueryString + "\n"
                + canonicalHeaders + "\n" + signedHeaders + "\n" + "e075474bd74294cb50ac67d7302a86719cd9dfa46142ee64dd5526539da28f20";
       // String data = "POST\n/industry-cgi\n\ncontent-type:application/json; charset=utf-8\ncontent-type\ne075474bd74294cb50ac67d7302a86719cd9dfa46142ee64dd5526539da28f20";
        String key = "";
        System.out.println(sha256X16(canonicalRequest, "utf-8"));
        //System.out.println(sha2561(data.getBytes("GBK")));
    }
    /**
     * sha256计算后进行16进制转换
     *
     * @param data 待计算的数据
     * @param encoding 编码
     * @return 计算结果
     */
    public static String sha256X16(String data, String encoding) {
        byte[] bytes = sha256(data, encoding);
        StringBuilder sha256StrBuff = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            if (Integer.toHexString(0xFF & bytes[i]).length() == 1) {
                sha256StrBuff.append("0").append(
                        Integer.toHexString(0xFF & bytes[i]));
            } else {
                sha256StrBuff.append(Integer.toHexString(0xFF & bytes[i]));
            }
        }
        return sha256StrBuff.toString();
    }


    /**
     * sha256计算
     *
     * @param datas 待计算的数据
     * @param encoding  字符集编码
     * @return
     */
    private static byte[] sha256(String datas, String encoding) {
        try {
            return sha256(datas.getBytes(encoding));
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    /**
     * sha256计算.
     * @param data 待计算的数据
     * @return 计算结果
     */
    private static byte[] sha256(byte[] data) {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-256");
            md.reset();
            md.update(data);
            return md.digest();
        } catch (Exception e) {
            return null;
        }
    }



}
